﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;



namespace Defector
{
    /// <summary>
    /// Interaction logic for Login.xaml
    /// </summary>
    public partial class Login : Window
    {
        public Login()
        {
            InitializeComponent();
        }

        private void loginButton_Click(object sender, RoutedEventArgs e)
        {

            login();

        }

        //If enter is pressed in the password field 
        private void passwordInput_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                login();
        }

        //If enter is pressed in the username field
        private void emailInput_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                login();
        }

        public void login()
        {
            SqlConnection con = new SqlConnection("Data Source=devinwatson.com;Initial Catalog=DefectEntities;User ID=Defects;Password=csharris");
            con.Open();
            SqlCommand cmd = new SqlCommand("Select * from People where Email='" + emailInput.Text + "'  and Password='" + passwordInput.Password + "'", con);
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd;
            DataSet dataSet = new DataSet();
            adapter.Fill(dataSet, "People");
            
            
            if (dataSet.Tables[0].Rows.Count > 0)
            {
                MainWindow main = new MainWindow();
                main.Show();
                Application.Current.MainWindow = main;
                DataRow user = dataSet.Tables["People"].Rows[0];
                main.userID = Convert.ToInt32(user.ItemArray.GetValue(0).ToString());
                main.firstName = user.ItemArray.GetValue(1).ToString();
                main.lastName = user.ItemArray.GetValue(2).ToString();
                main.con = con;
                this.Close();
            }
            else
            {

                errorLabel.Content = "Error! Login not found!";

            }

            con.Close();
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            Environment.Exit(0);
        }




    }
}
